/*
 * Copyright (c) 2006, 2021, webrx.cn All rights reserved.
 *
 */
package cn.webrx.ls.controller;

import com.wf.captcha.GifCaptcha;
import com.wf.captcha.utils.CaptchaUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>Project: likeshop - AdminController
 * <p>Powered By webrx
 * <p>Created By IntelliJ IDEA On 2021-04-02 09:50:58
 * <p>Description :
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 15
 */
@Controller
@RequestMapping("/admin")
public class AdminController {
    @GetMapping("login")
    public void login() {
    }

    @GetMapping("captcha")
    public void captcha(HttpServletResponse resp, HttpServletRequest req) throws IOException {
        GifCaptcha c = new GifCaptcha();
        CaptchaUtil.out(c, req, resp);
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        //session.invalidate();
        session.removeAttribute("account");
        return "redirect:/";
    }

    // /admin/   就直接打开http://localhost/admin/
    @GetMapping(value = {"/", "/index"})
    public String index() {
        return "admin/index";
    }


    @PostMapping("check")
    @ResponseBody
    public Map<String, Object> check(String account, String password, String code, String rememberme, HttpServletRequest req) {
        Map<String, Object> map = new HashMap<>();
        if (CaptchaUtil.ver(code, req)) {
            CaptchaUtil.clear(req);  //  清除session中的验证码
            if ("admin".equals(account) && "123456".equals(password)) {
                map.put("code", 1);
                map.put("msg", "登录成功 loading...");
                //token
                HttpSession session = req.getSession();
                session.setAttribute("account", account);
            } else {
                map.put("code", 0);
                map.put("msg", "账号密码错误，登录失败.");
            }
        } else {
            map.put("code", 0);
            map.put("msg", "验证码错误.");
        }
        return map;
    }
}
